var createError = require('http-errors');
var express = require('express');
var session = require('express-session')
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

// 引入工具类
var jwtUtils = require('./utils/jwtUtil')

var indexRouter = require('./routes/index');
// ① 引用路由
var usersRouter = require('./routes/users');

var app = express();
//配置中间件 maxAge单位为ms
app.use(session({
    secret: "keyboard cat",
    resave: false,
    saveUninitialized: true,
    cookie: ('name', 'value',{maxAge:  5*60*1000,secure: false})
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 定义全局的加解密秘钥
global.globalKey = '123456'

app.use(async function(req,resp,next){
    let path = req.path

    if (path.startsWith('/users/login')) {
        next()
    } else {
        // 从请求头里头拿到令牌 (常规情况)
        let token = req.headers.token;
        if (!token) {
            // 非常规情况（文件下载，是不是没有办法设置请求头，或者比如获取验证码）
            token = req.query.token;
        }
        let result = await jwtUtils.verifysync(token, global.globalKey)
        if (result.err) {
            // console.log(111)
            // resp.send(result.err)
            // throw new Error(result.msg)
            resp.status(500)
            resp.send(result.msg)
        } else {
            req.headers.session = result
            // 表示执行下一步动作
            next();
        }
    }

    // if(req.path !='/mine.html' && req.path !='/user/login' && req.path !='/user/register'){
    //     let token = req.headers.token;
    //     safeInterceptor.verify(token,global.secretKey,function(user){
    //         req.headers.sessionData = user;
    //         next();
    //     },function(err){
    //         next();
    //     })
    // }else{
    //     next();
    // }
})

app.use('/', indexRouter);
// ② 路由注册
app.use('/users', usersRouter);

// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   // next(createError(404));
//     // 改写框架 捕获404异常
//     res.status(500)
//     res.send('404')
// });

// error handler
app.use(function(err, req, res, next) {
    // 改写5xx异常
    res.status(500)
    res.send(`[error-msg]${err.message}`)// res.send()
});

module.exports = app;
